package com.dgz.springboot18.shiro;


import com.dgz.springboot18.pojo.AdminInfo;
import com.dgz.springboot18.service.AdminService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 自定义realm
 */
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private AdminService service;

    /**
     * 执行授权逻辑
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //给资源进行授权
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获取当前登陆用户
        Subject subject = SecurityUtils.getSubject();
        AdminInfo adminInfo = (AdminInfo) subject.getPrincipal();
        //授权,通过遍历，将adminInfo对象中的角色和权限都打包到info对象中
        System.out.println(adminInfo);
        info.addRole("teacher");
        info.addStringPermission(adminInfo.getAdminTask());
        return info;
    }

    /**
     * 执行认证逻辑,
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //获得UsernamePasswordToken对象
        UsernamePasswordToken token=(UsernamePasswordToken)authenticationToken;
        AdminInfo adminInfo=new AdminInfo();
        adminInfo.setAdminName(token.getUsername());
        AdminInfo result = service.queryByAccount(adminInfo);
        //判断用户名是否存在
        if (result==null){
            return null;
        }
        //将密码交给shiro判断，并且返回这个对象,在授权中获取
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                result,                           //用户对象
                result.getAdminPassword(),             //用户密码
                ByteSource.Util.bytes(result.getSalt()),  //盐
                getName()
        );
        return info;
    }



}
